import { ref, shallowRef, toRefs, reactive, computed, watch, watchEffect, onMounted, h } from "vue";
import { systemInfo } from "../tools/system.js";
import { onShow, onLoad } from "@dcloudio/uni-app";
import { showToast } from "vant";
import { useStore } from "vuex";
import { useI18n } from "vue-i18n";
import ApiOptions from "../api/index.js";
import { getRouteParams, logout } from "../tools/tools.js";
import { useApi, useJumpPage, useHideTabbar as useHide } from "./open.js";
import { sort } from "../lang/lanOptions.js";
import { useComModel, useContentHeight, useLanState, useThemeState } from "./common.js";

export const useHideTabbar = useHide;
// ------------------------------ function hooks ------------------------------
/** 用户线上配置 */
export const useUserOnlineConfig = () => {
  const store = useStore();
  const config = ref([]);
  const state = ref({});

  onShow(() => {
    config.value = Object.values(store.getters["user/getUserConfig"]);
    config.value.forEach((item) => (state.value[item.name] = ""));
  });

  return {
    userConfig: config,
    userConfigState: state,
  };
};

/** 用户本地设置 */
export const useSetting = () => {
  const store = useStore();

  const minHeight = useContentHeight();
  const [showModel, handleModel] = useComModel();
  const [curLanguage] = useLanState(store);
  const [isDark, setTheme] = useThemeState(store);

  return {
    showModel,
    handleModel,
    curLanguage,
    isDark,
    setTheme,
    minHeight,
  };
};

/** 用户登录表单页面高度
 * @param {*} infoHeight 登录页用户logo信息高度
 */
export const useLoginFormPageParams = (infoHeight) => {
  const formHeight = ref("auto");
  onMounted(() => {
    const { windowHeight, windowTop } = systemInfo();

    formHeight.value = windowHeight - windowTop - infoHeight + "px";
  });

  return [formHeight];
};

/** 获取用户状态 */
export const useUserState = () => {
  const store = useStore();
  const isLogin = ref(false);
  const isOver = ref(false);
  const avatar = ref("");

  const loginState = computed(() => {
    return store.getters["user/isLogin"];
  });

  watchEffect(() => {
    isLogin.value = loginState.value;
    isOver.value = store.getters["user/isOverDate"];
    avatar.value = store.state.user.base.avatar;
  });

  return {
    avatar,
    isLogin,
    isOver,
    loginState,
  };
};

/** 初始化头部事件
 * @param {*} position
 * @returns
 */
export const useInitHeader = (position) => {
  function confirmModel() {
    return new Promise((resolve) => {
      uni.showModal({
        title: "提示",
        content: "订单还未确认，确定取消吗？",
        showCancel: true,
        success: ({ confirm, cancel }) => {
          resolve(confirm);
        },
      });
    });
  }

  // 路由回退
  async function onClickLeft(valid) {
    if (position === "mine") return;
    if (!valid || (valid && (await confirmModel()))) uni.navigateBack({ delta: 1 });
  }

  async function toPersional(valid) {
    if (!valid || (valid && (await confirmModel()))) uni.switchTab({ url: "/pages/member/index" });
  }

  return { onClickLeft, toPersional };
};

/** 复制文本 */
export const useCopyText = () => {
  const onCopy = (text) => {
    uni.setClipboardData({
      data: text,
      success: () => {
        // showToast("复制成功");
      },
    });
  };

  return {
    onCopy,
  };
};

/** 获取所有单页 */
export const useGetAllSinglePage = (list, to) => {
  const splitLists = shallowRef([]);
  const result = {};
  const currentIndex = ref(0);
  const total = ref(0);
  const [getAllPages, store] = useApi("getAllPages");

  const defaultTemp = {
    click: (id) => to(id),
    config: {
      size: 35,
      strokeWidth: 2,
    },
  };

  const onChange = (index) => {
    currentIndex.value = index;
  };

  const getSplitLists = () => {
    const list = splitLists.value.slice(Number(!store.getters["user/isLogin"]));
    total.value = list.length;
    return splitLists.value.slice();
  };

  onLoad(async () => {
    const { data: signleList } = await getAllPages();
    list.push(...signleList.map((i) => ({ ...i, ...defaultTemp })));
    splitLists.value.length = 0;
    splitLists.value = list.reduce((pre, cur, index) => {
      const key = Math.floor(index / 8);
      if (!pre[key]) pre[key] = [];
      pre[key].push(cur);

      return pre;
    }, []);
    total.value = splitLists.value.length;
  });

  return { getSplitLists, onChange, currentIndex, total };
};

/** 我的账单信息 */
export const useMyBill = (targetList) => {
  const store = useStore();
  const history = store.getters["user/getUserHistory"];

  const setAnimationToCount = (model, start, end, duration) => {
    const time = Math.floor(Math.max(Math.min(4000 / (end - start), 120), 59));
    const range = duration / time;
    const step = Math.max((end - start) / range, 1);
    let count = 0;

    const interval = setInterval(() => {
      model.value = Math.floor(start + step * ++count);
      if (count >= range || model.value >= end) {
        model.value = end;
        clearInterval(interval);
      }
    }, time);
  };

  onLoad(() => {
    ["total_orders", "total_order_quantity", "total_order_amount", "total_paid_amount"].map((i, k) => {
      setAnimationToCount(targetList[k].value, 0, Number(history[i]), 3000);
    });
  });

  return { history };
};

/** 我的服务跳转分发 */
export const useMyServer = () => {
  const [to] = useJumpPage();

  const toMyAddress = () => to`${"/pages/member/address/address"}`;
  const toHelpPage = () => uni.navigateTo({ url: `${"/pages/member/help/help"}` });
  const toSinglePage = (page) => uni.navigateTo({ url: `${"/pages/member/help/single?current=" + page}` });
  const toMessagePage = () => to`${"/pages/member/message/message"}`;
  const toFuture = () => to`${"/pages/member/future/future"}`;
  const toFavoriteList = () => to`${"/pages/member/favorite/favorite"}`;
  const toMemberInfo = () => to`${"/pages/member/info/info"}`;
  const toSettingPage = () => to`${"/pages/member/setting/setting"}`;
  const toChatPage = () => to`${"/pages/chat/chat"}`;

  return {
    toMyAddress,
    toHelpPage,
    toSinglePage,
    toMessagePage,
    toFuture,
    toFavoriteList,
    toMemberInfo,
    toSettingPage,
    toChatPage,
  };
};

/** 监听和处理单页信息, 截取单页地址栏配置 */
export const usePageQuery = () => {
  const type = ref("");
  onShow(() => {
    type.value = getRouteParams("current");
  });

  return [type];
};

/** 初始化应用页面高度 */
export const useInitPageBoundary = () => {
  const contentHeight = ref("auto");
  onMounted(() => {
    const { windowHeight, windowTop } = systemInfo();
    contentHeight.value = windowHeight - windowTop + "px";
  });

  return {
    minHeight: contentHeight,
  };
};

/** 初始化A4纸缩放动画 */
export const useA4Transform = () => {
  const width = 1240;

  // 处理A4纸样式
  const A4_style = ref({
    transform: "scale(1)",
  });

  onMounted(() => {
    const { windowWidth } = systemInfo();

    const radio = windowWidth / width;
    const mov_x = (width - windowWidth) / 2;
    const mov_y = ((width - windowWidth) / 2) * 1.414;

    console.log(radio, mov_x, mov_y);

    A4_style.value.width = width + "px";
    A4_style.value.transform = `scale(${radio})`;
  });

  return [A4_style];
};

/** 分页钩子 */
export const usePagination = (totalItems = 100, itemsPerPage = 16, defaultSort = 0) => {
  const currentPage = ref(1);
  const pageSize = ref(itemsPerPage);
  const sort = ref(defaultSort);
  const total = ref(0);

  const handlePageChange = (page) => {
    currentPage.value = page;
  };

  const handlePageSizeChange = (size) => {
    currentPage.value = 1;
    sort.value = defaultSort; // 页数改变时，重置排序方式为默认值
    pageSize.value = size;
  };

  const handleSortChange = (newSort) => {
    sort.value = newSort;
  };

  return {
    page: currentPage,
    size: pageSize,
    sort,
    total,
    handlePageChange,
    handlePageSizeChange,
    handleSortChange,
  };
};

// ------------------------------ business hooks ------------------------------
// 配置业务功能

/** 用户登录钩子 */
export const useLogin = () => {
  const store = useStore();

  const form = ref({
    username: "",
    password: "",
  });

  const onSubmit = async () => {
    // 登录验证
    const result = await store.dispatch("user/doLogin", form.value);

    if (result.code == 1) {
      showToast(result.message);
      return uni.switchTab({ url: "/pages/member/index" });
    }

    return uni.showModal({
      title: "登录失败",
      content: result.message,
      showCancel: false,
      confirmText: "确认",
      success: (res) => {},
      fail: () => {},
      complete: () => {},
    });
  };

  return [form, onSubmit];
};

/** 初始化订单详情 */
export const useOrderDetailInit = () => {
  const contentHeight = ref("auto");
  onMounted(() => {
    const { windowHeight, windowTop } = systemInfo();

    contentHeight.value = windowHeight - windowTop + "px";
  });

  return {
    minHeight: contentHeight,
  };
};

/** 获取列表信息 */
export const useListState = (apiSign = "getHomeList") => {
  const { page, size, sort, total } = usePagination();
  const list = ref([]);

  const [postApi, store] = useApi(apiSign);

  const requestData = async (params) => {
    const res = await postApi(
      Object.assign(
        {
          page: page.value,
          size: size.value,
          sort: sort.value,
          itemType: 0,
        },
        params
      )
    );

    if (res.code === 1) {
      const result = res.data.list.map((item) => ({
        productStatus: "normal",
        saleStatus: "hot",
        price: item.price,
        date: item.created_at,
        ...item,
      }));

      page.value = res.data.page;
      total.value = res.data.total;
      return result;
    }

    return [];
  };

  const refresh = async function () {
    list.value.length = 0;
    const data = await requestData(...arguments);
    list.value.push(...data);
  };

  const loadMore = async () => {
    page.value = page.value + 1;
    const more = await requestData();
    list.value.push(...more);
  };

  onShow(async () => {
    if (list.value.length) {
      const price_1 = list.value[0].price;
      isNaN(Number(price_1)) && store.getters["user/isLogin"] && refresh();

      return;
    }
    const data = await requestData();
    list.value.push(...data);

    console.log(total.value === list.value.length);
  });

  return { list, loadMore, refresh, total };
};

/** 获取分类信息 */
export const useCategoryState = () => {
  const brandList = ref([]);
  const cateList = ref([]);

  async function requestData() {
    return await Promise.all(
      ["getBrand"].map(async (url) => {
        const res = await ApiOptions[url]();
        return res.data;
      })
    );
  }

  onLoad(async () => {
    if (brandList.value.length) return;
    const res = await requestData();
    const data = res[0];

    const result = data["level-2"].map((item) => ({
      value: item.id,
      text: item.ename,
    }));

    cateList.value.push(
      ...data["level-3"].map((item) => ({
        value: item.id,
        text: item.ename,
      }))
    );

    brandList.value.push(...result);
  });

  return [brandList, cateList];
};

/** 获取商品信息 */
export const useProductDetailInit = () => {
  const productDetail = ref({
    pics: [],
  });
  const productId = ref(0);
  const nums = ref(0);
  const time = ref(0);
  const isNew = ref(false);
  const isHot = ref(false);

  uni.showTabBar();

  const [getProductDetail, store] = useApi("getProductDetail");

  onShow(async () => {
    productId.value = getRouteParams("id");

    const res = await getProductDetail({
      id: productId.value,
    });

    const detail = res.data.detail;

    productDetail.value = res.data.detail;
    nums.value = detail.moq;
    isNew.value = detail.created_at?.substring(0, 10) === new Date().toISOString().substring(0, 10);
    isHot.value = detail.recied === 1;
    time.value = detail.openDateTime * 1000 - new Date().getTime();

    store.dispatch("history/add", productDetail.value)
  });

  return {
    productDetail,
    time,
    productId,
    nums,
  };
};

/** 处理商品事件 */
export const useProductDetailEvent = () => {
  const [addToFavourite, store] = useApi("addToFavourite");

  const addCartItem = (item) => {
    store.dispatch("cart/addCartItem", item);
  };
  const addFarvorite = async (id) => {
    if (!store.getters["user/isLogin"]) {
      showToast("请先登录");
      return false;
    }
    const res = await addToFavourite({ itemId: id });
    if (res.code === 1) {
      showToast("收藏成功");
      return true;
    }
    return false;
  };

  return {
    addCartItem,
    addFarvorite,
  };
};

/** 处理购物车列表信息 */
export const useCartListInit = () => {
  const list = ref([]);
  const total = ref(0);
  const totalPrice = ref(0);
  const allChecked = ref(false);
  const [confirmOrder, store] = useApi("confirmOrder");

  const { loginState, isLogin } = useUserState();

  const onALLChecked = (val) => {
    list.value.forEach((item) => {
      item.limit && (item.checked = val);
    });
  };

  const getCartList = async () => {
    const res = await store.dispatch("cart/getCartList", loginState.value);
    list.value = res;
    //console.log(list.value);
  };

  const updateCartItem = async (item) => {
    await store.dispatch("cart/updateCartItem", item);
  };

  const deleteCartItem = async (item) => {
    await store.dispatch("cart/deleteCartItem", item);
    getCartList();
  };

  const handleNumChecked = () => {
    let all = true,
      none = false;
    list.value.map((cur) => {
      none = none || cur.checked;
      all = all && cur.checked;
    });

    all && (allChecked.value = true);
    !none && (allChecked.value = false);
  };

  const toConfirmOrder = async () => {
    if (!isLogin.value) {
      return showToast("请先登录");
    }
    if (total.value === 0) {
      return showToast("请先添加商品");
    }

    const res = await confirmOrder({
      addressId: store.getters["user/getUserDefaultAddressId"] || null,
      goods_info: JSON.stringify(
        list.value
          .filter((item) => item.checked)
          .map((i) => ({
            id: i.id,
            number: i.nums,
          }))
      ),
    });

    if (res.code !== 1) return;

    list.value = list.value.filter((item) => item.checked !== true);

    // 删除勾选的商品
    store.dispatch("cart/updateList", list.value);

    uni.navigateTo({
      url: "/pages/order/confirm?orderno=" + res.data.orderno,
    });
  };

  onShow(async () => {
    uni.hideTabBar();
    getCartList();
  });

  watch(
    list,
    () => {
      const selectedList = list.value.filter((item) => item.checked === true);

      if (selectedList.length || selectedList.length === 0) {
        total.value = selectedList.length;

        totalPrice.value = selectedList.reduce((pre, cur) => {
          pre = pre + cur.nums * Number(cur.price);
          return pre;
        }, 0);
      }
    },
    {
      deep: true,
      immediate: true,
    }
  );

  return {
    list,
    total,
    isLogin,
    totalPrice,
    allChecked,
    onALLChecked,
    handleNumChecked,
    deleteCartItem,
    updateCartItem,
    toConfirmOrder,
  };
};

export const useSinglePageView = () => {
  const single = ref({
    title: "",
    content: "",
  });
  onShow(async () => {
    let curPage = getCurrentPages();
    let route = curPage[curPage.length - 1].route; //获取当前页面的路由
    let options = curPage[curPage.length - 1].options; //获取当前页面参数，如果有则返回参数的对象，没有参数返回空对象{}

    // 1 about 2copyright 3contact
    const res = await ApiOptions.getSingle({
      id: options.current,
    });
    single.value.title = res.data.page[0].title;
    single.value.content = res.data.page[0].content;
  });

  return [single];
};

export const useHelpPageView = () => {
  const list = ref([]);
  onShow(async () => {
    const res = await ApiOptions.getArticleFaqList();
    list.value = res.data.data;
  });

  return [list];
};

/** 用户地址信息 */
export const useAddressInfo = () => {
  const list = ref([]);
  const [getUserAddressList, deletUserAddressList, setDefaultAddress] = useApi([
    "getUserAddressList",
    "deletUserAddressList",
    "setDefaultAddress",
  ]);

  const onDelete = async (id) => {
    const res = await deletUserAddressList({ id });
    if (res.code !== 1) return showToast(res.message);
    list.value = list.value.filter((item) => item.id !== id);
    showToast("删除成功");
  };

  const setDefault = async (id) => {
    const res = await setDefaultAddress({ id });
    if (res.code !== 1) return showToast(res.message);
    list.value.map((item) => {
      if (item.id === id) {
        item.isDefault = 1;
      } else {
        item.isDefault = 0;
      }
    });
    showToast("设置成功");
  };

  const getList = async () => {
    const res = await getUserAddressList();
    list.value = res.data;
  };

  onShow(async () => {
    if (list.value.length) return;
    getList();
  });

  return [list, onDelete, setDefault];
};

/** 编辑用户地址信息 */
export const useEditAddressInfo = () => {
  let countries = [];
  const [
    getWorldArea,
    getCountryList,
    getCountryByIp,
    deletUserAddressList,
    editUserAddress,
    addUserAddress,
    getUserAddressById,
    store,
  ] = useApi([
    "getWorldArea",
    "getCountryList",
    "getCountryByIp",
    "deletUserAddressList",
    "editUserAddress",
    "addUserAddress",
    "getUserAddressById",
  ]);

  const countryOptions = ref([]);
  const worldAreaOptions = ref([]);
  const isEdit = ref(false);

  const config = ref({
    left: "取消",
    right: "保存",
  });

  const form = ref({
    aCountry: "",
    companyName: "",
    postcode: "",
    aProvince: "",
    aCity: "",
    aDetail: "",
    fName: "",
    lName: "",
    email: "",
    phone: "",
    isDefault: false,
    aCont: "",
    private: "",
  });

  const deleteAddress = async (id) => {
    await deletUserAddressList({ id });
    uni.navigateTo({ url: "/pages/member/address/address" });
    showToast("删除成功");
  };

  const editAddress = async (params) => {
    await editUserAddress(params);
    showToast("编辑成功");
  };

  const addAddress = async (params) => {
    await addUserAddress(params);
    uni.navigateTo({ url: "/pages/member/address/address" });
    showToast("添加成功");
  };

  const resetCountries = (continent) => {
    countryOptions.value = countries
      .filter((i) => i.continent === continent)
      .map(({ id, name }) => ({
        text: name,
        value: id,
      }));

    form.value.aCont = continent;
    form.value.aCountry = countryOptions.value[0].text;
  };

  const initEdit = async () => {
    isEdit.value = getRouteParams("current") === "edit";

    if (isEdit.value) {
      const id = Number(getRouteParams("id"));
      const res = await getUserAddressById({ id });
      config.value.left = "删除";

      Object.assign(form.value, store.getters["config/getEditAddress"]);
      res.code === 1 && Object.assign(form.value, res.data);
    }

    let areas = uni.getStorageSync("worldArea") || [];
    countries = uni.getStorageSync("countrys") || [];

    if (!areas.length) {
      getWorldArea().then((res) => {
        const result = res.data.map(({ id, name }) => ({
          text: name,
          value: id,
        }));
        worldAreaOptions.value = result;
        uni.setStorage({
          key: "worldArea",
          data: res.data,
        });
      });
    } else {
      worldAreaOptions.value = areas.map(({ id, name }) => ({
        text: name,
        value: id,
      }));
    }

    if (!countries.length) {
      const res = await getCountryList();
      const result = res.data.map(({ id, name }) => ({
        text: name,
        value: id,
      }));
      countryOptions.value = result;
      uni.setStorage({
        key: "countrys",
        data: res.data,
      });
    }

    if (!form.value.aCountry) {
      const res = await getCountryByIp();
      form.value.aCountry = res.data;
    }

    const country = countries.find((i) => i.name === form.value.aCountry);
    form.value.aCont = country.continent;

    countryOptions.value = countries
      .filter((i) => i.continent === country.continent)
      .map(({ id, name }) => ({
        text: name,
        value: id,
      }));
  };

  return {
    config,
    form,
    initEdit,
    resetCountries,
    countryOptions,
    worldAreaOptions,
    onDelete: () => {
      isEdit.value ? deleteAddress(form.value.id) : uni.navigateBack();
    },
    onSave: function () {
      const params = ((form) => {
        const { countNum, created_at, deleted_at, updated_at, ...rest } = form.value;
        return {
          ...rest,
          ...{
            private: form.value.private ? 1 : 0,
            isDefault: form.value.default ? 1 : 0,
          },
        };
      })(form);

      isEdit.value ? editAddress(params) : addAddress(params);
    },
  };
};

/** 我的收藏 */
export const useMyFavorite = () => {
  const list = ref([]);
  const [getFavouriteList] = useApi("getFavouriteList");
  const [deleteFromFavourite] = useApi("deleteFromFavourite");

  const deleteFavourite = async (id) => {
    const res = await deleteFromFavourite({ id });
    if (res.code !== 1) return showToast("删除失败");

    list.value = list.value.filter((item) => item.id !== id);
  };

  onShow(async () => {
    if (list.value.length) return;
    const res = await getFavouriteList();
    list.value = res.data.filter((i) => Boolean(i.itemId));
  });

  return [list, deleteFavourite];
};

/** 未来计划内容 */
export const useFuturePlan = () => {
  const list = ref([]);
  const dateList = ref([]);
  const [getFuturePlanList] = useApi("getFuturePlanList");

  const formatter = (day) => {
    const date = day.date.toISOString().substring(0, 10);
    dateList.value.includes(date) && (day.bottomInfo = "查看计划");
    return day;
  };

  const loadMonthPlain = async (month) => {
    const today = new Date();
    month = month || today.getMonth() + 1;

    const res = await getFuturePlanList({
      pid: 0,
      year: today.getFullYear(),
      month,
    });
    list.value.push(...res.data);
    dateList.value.push(...res.data.map((item) => item.firstDate));
  };

  const onMonthShow = (day) => {
    loadMonthPlain(day.date.getMonth() + 1);
  };

  return { list, dateList, formatter, onMonthShow };
};

export const useTestApi = async (sign = "getCartPrice") => {
  const res = await ApiOptions[sign]({
    ids: JSON.stringify([142, 143, 144]),
  });
  console.log(res);
};

export const useForgetPasswordHander = () => {
  const EMAIL_REGS = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/; //邮箱校验

  const form = ref({
    username: "",
    captcha: "",
    password: "",
    confirmPassword: "",
  });

  // 获取验证码
  const getValidCode = async () => {
    if (!EMAIL_REGS.test(form.value.username)) return showToast("请输入正确的邮箱");

    const res = await ApiOptions.sendVerifyCode({
      username: form.value.username,
      type: "warning",
    });
    return showToast(res.message);
  };
  // 找回密码
  const handleForgetPassword = async () => {
    const res = await ApiOptions.retrievePassword(form.value);
    res.code === 1 && showToast(res.message);

    return uni.navigateTo("/pages/member/login/login");
  };

  const validRePassword = () => {
    return new Promise((resolve, reject) => {
      if (form.value.password !== form.value.confirmPassword) {
        resolve("两次密码输入不一致");
      } else {
        resolve();
      }
    });
  };

  return {
    form,
    getValidCode,
    handleForgetPassword,
    validRePassword,
  };
};

export const useRecommend = () => {
  const recommendList = ref([]);
  const total = ref(0);

  const getRecommendList = async () => {
    if (recommendList.value.length) return;
    const res = await ApiOptions.getRecommend();
    recommendList.value = res.data.list;
    total.value = res.data.total;
  };

  onShow(() => {
    getRecommendList();
  });

  return [recommendList, total];
};

export const useUserRegisterHander = () => {
  const EMAIL_REGS = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/; //邮箱校验

  const info = ref({
    item: "",
    desc: "",
    num: 30,
    experience: true,
    freight: true,
    payment: [],
  });

  const form = ref({
    clientType: "",
    username: "",
    verify_code: "",
    password: "",
    country: "",
  });

  const merge_form = reactive({
    password_2: "",
    ...toRefs(form.value),
    ...toRefs(info.value),
  });

  /** 获取验证码 */
  const getValidCode = async () => {
    if (!EMAIL_REGS.test(form.value.username)) return showToast("请输入正确的邮箱");

    const res = await ApiOptions.sendVerifyCode({
      username: form.value.username,
      type: "warning",
    });
    return showToast(res.message);
  };

  /** 注册用户 */
  const registerUser = async (params) => {
    const res = await ApiOptions.registerUser(params);

    return res.code === 1 ? uni.reLaunch({ url: "/pages/member/login/login" }) : showToast(res.message);
  };

  /** 保存注册信息 */
  const onSaveRegisterInfo = async () => {
    const res = await ApiOptions.saveProfile({
      info: JSON.parse(info.value),
      ...form.value,
    });

    return res.code === 1 ? showToast("保存成功") : showToast(res.message);
  };

  /** 编辑用户信息 */
  const editUserInfo = async () => {
    const res = await ApiOptions.editUserInfo();

    return res.code === 1 ? showToast("编辑成功") : showToast(res.message);
  };

  /** 获取用户信息 */
  const getUserInfo = async () => {
    const res = await ApiOptions.getUserInfo();
    return res.code === 1 ? res.data : null;
  };

  return {
    form,
    info,
    merge_form,
    getValidCode,
    registerUser,
    onSaveRegisterInfo,
    editUserInfo,
    getUserInfo,
  };
};

export const useUserinfoHandler = () => {
  const result = useUserRegisterHander();
  const detail = ref({});
  const mergeData = ref({});

  onShow(async () => {
    const data = await result.getUserInfo();
    data.address_list = data.address_list[0] || {};
    detail.value = data;
    detail.value.name = data.address_list.fName + " " + data.address_list.lName || "";

    mergeData.value = { ...toRefs(detail.value.memberData), ...toRefs(detail.value.businessData) };
  });

  return { detail, mergeData, ...result };
};

export const useOrderItemJumpHandler = () => {
  const [to] = useJumpPage();

  const toOrderDetail = (orderno) => to`${"/pages/order/detail/index?orderno=" + orderno}`;
  const viewLogistics = (num, name) => to`${"/pages/order/logistics?id=" + num + "&name=" + name}`;
  const toSaleInvoice = (orderno) => to`${"/pages/order/invoice?orderno=" + orderno}`;

  return {
    toOrderDetail,
    viewLogistics,
    toSaleInvoice,
  };
};

export const useGetOrderList = () => {
  const total = ref(1000);
  const orderList = ref([]);
  const orderStatusMap = ref({});
  const [getList, cancelOrderById, store] = useApi(["getOrderList", "cancelOrder"]);
  const menuOptions = ref([]);
  const currentStatus = ref(1000);
  const currentSort = ref(0);
  const loading = ref(false);
  const page = ref(1);

  const getOrderList = async () => {
    const res = await getList({
      page: page.value,
      size: 10,
      status: currentStatus.value === 1000 ? null : currentStatus.value,
      sort: currentSort.value,
    });
    total.value = res.data.total;
    orderList.value.push(...res.data.list);
  };

  const refreshOrderList = (pos, val) => {
    if (pos === "orderStatus") currentStatus.value = val;
    else currentSort.value = val;
    orderList.value.length = 0;
    getOrderList();
  };

  const cancelOrder = (orderId) => {
    uni.showModal({
      title: "提示",
      content: "确认要删除订单吗？",
      showCancel: true,
      success: async () => {
        const res = await cancelOrderById({ orderId });
        if (res.code === 1) {
          showToast("取消成功");
          orderList.value.length = 0;
          getOrderList();
        } else showToast(res.message);
      },
    });
  };

  const loadMore = async () => {
    page.value++;
    await getOrderList();
    loading.value = false;
  };

  onShow(() => {
    currentStatus.value = Number(getRouteParams("type") || 1000);
    getOrderList();

    orderStatusMap.value = store.getters["user/getOrderStatusMap"][store.getters["config/isZh"] ? "zh" : "en"];

    menuOptions.value = Object.values(orderStatusMap.value).map((i, k) => ({ text: i, value: k }));
    menuOptions.value.unshift({
      text: "全部",
      value: 1000,
    });
  });

  return {
    total,
    currentStatus,
    currentSort,
    orderList,
    orderStatusMap,
    refreshOrderList,
    menuOptions,
    cancelOrder,
    loading,
    loadMore,
  };
};

export const useGetOrderDetail = () => {
  const detail = ref({});
  const address = ref("");
  const mapper = ref({});
  const [getDetail, store] = useApi("getOrderDetail");

  const getOrderDetail = async (orderno) => {
    const res = await getDetail({ orderno });
    detail.value = res.data;
    address.value = res.data.address || "";
  };

  const init = () => {
    return () => {
      mapper.value = store.getters["user/getOrderStatusMap"][store.getters["config/isZh"] ? "zh" : "en"];

      const orderno = getRouteParams("orderno");
      if (!orderno) return showToast("订单号不存在");
      getOrderDetail(orderno);
    };
  };

  onShow(init());

  return {
    detail,
    address,
    mapper,
  };
};

export const useSearch = () => {
  const list = ref([]);
  const type = ref(getRouteParams("current"));
  const orderStatusMap = ref({});
  const menuOptions = ref([]);

  const currentStatus = ref(1000);
  const currentSort = ref(0);

  const [searchInfo, store] = useApi(type.value === "order" ? "searchOrders" : "searchProducts");

  const searchList = async (keyword) => {
    const params = {
      page: 1,
      size: 10,
      keyword,
      sort: currentSort.value,
    };
    type.value === "order" && (params.status = currentStatus.value === 1000 ? null : currentStatus.value);
    const res = await searchInfo(params);
    list.value = res.data.list;
  };

  const refreshSearchOrderList = (pos, val) => {
    if (pos === "orderStatus") currentStatus.value = val;
    else currentSort.value = val;
    searchList();
  };

  onShow(() => {
    orderStatusMap.value = store.getters["user/getOrderStatusMap"][store.getters["config/isZh"] ? "zh" : "en"];

    menuOptions.value = Object.values(orderStatusMap.value).map((i, k) => ({ text: i, value: k }));
    menuOptions.value.unshift({
      text: "全部",
      value: 1000,
    });
  });

  return {
    currentStatus,
    currentSort,
    orderStatusMap,
    list,
    type,
    searchList,
    menuOptions,
    refreshSearchOrderList,
  };
};

/** 物流页面 */
export const useLogistics = () => {
  const trackDetail = ref({});

  const [getTrackByNumber] = useApi("getTrackByNumber");

  const getTrackDetail = async (id) => {
    id = getRouteParams("id");
    const res = await getTrackByNumber({
      id: id,
      //trackingNumber: "775777625188",
      // courier_code: ''
    });
    trackDetail.value = res.data;
  };

  onShow(() => {
    getTrackDetail();
  });

  return {
    trackDetail,
    getTrackDetail,
  };
};

/** 下单页面 */
export const useCreateOrder = () => {
  const [to] = useJumpPage();
  const detail = ref({
    ShipType: {},
    order_items: [],
    address_list: [],
  });
  const [submitOrder, getOrderDetail, getAddressList, store] = useApi([
    "submitOrder",
    "getOrderDetail",
    "getUserAddressList",
  ]);
  const columns = ref([]); // 海运方式
  const content = ref(""); // 备注
  const activeShipWay = ref({
    text: "",
    value: 1,
  });
  const showPicker = ref(false);
  const showAddressPicker = ref(false);
  const currentAddressDetail = ref({});
  const address = ref({
    text: "",
    value: "",
  });
  const tableData = ref([]);
  const addressList = ref([]);
  const addressListColumns = ref([]);

  const chooseShipWay = ({ selectedOptions }) => {
    Object.assign(activeShipWay.value, selectedOptions[0]);
    showPicker.value = false;
  };

  const chooseAddress = ({ selectedOptions }) => {
    Object.assign(address.value, selectedOptions[0]);
    currentAddressDetail.value = addressList.value.find((i) => i.id === address.value.value);
    showAddressPicker.value = false;
  };

  const submit = async () => {
    const orderno = getRouteParams("orderno");
    const res = await submitOrder({
      orderno: orderno,
      content: content.value,
      addressId: address.value.value,
      shipway: activeShipWay.value.value,
    });

    res.code === 1 && to`${"/pages/order/detail/index?orderno=" + orderno}`;
  };

  const getDetail = async (orderno) => {
    const res = await getOrderDetail({
      orderno: orderno,
    });
    if (res.code === 1) {
      detail.value = res.data;

      const items = res.data.order_items.map((i) => ({
        id: i.id,
        no: i.code,
        quantity: i.nums,
        unit: i.price,
      }));

      tableData.value = [
        ...items,
        ...[
          {
            id: "",
            no: "",
            quantity: res.data.total_nums,
            unit: res.data.subamount,
          },
        ],
      ];
    }
  };

  const initPage = async () => {
    getAddressList().then((res) => {
      addressList.value = res.data;
      addressListColumns.value = res.data.map(({ aProvince, aCity, aDetail, id }) => ({
        text: `${aProvince} ${aCity} ${aDetail}`,
        value: id,
      }));

      address.value.value = store.getters["user/getUserDefaultAddressId"] || res.data[0].id || 0;

      const currentAddress = res.data.find((i) => i.id === address.value.value);
      if (currentAddress) {
        currentAddressDetail.value = currentAddress;
        const { aProvince, aCity, aDetail } = currentAddress;
        address.value.text = `${aProvince} ${aCity} ${aDetail}`;
      }
    });
    await getDetail(getRouteParams("orderno"));
    columns.value = Object.entries(detail.value.ShipType).map(([key, value]) => ({ text: value, value: key }));

    Object.assign(activeShipWay.value, columns.value[0]);
  };

  onShow(initPage);

  return {
    submit,
    detail,
    address,
    tableData,
    columns,
    content,
    showPicker,
    showAddressPicker,
    activeShipWay,
    chooseShipWay,
    chooseAddress,
    addressList,
    addressListColumns,
    currentAddressDetail,
  };
};

export const useMemberConfig = () => {
  /** 编辑用户信息 */
  const editUserInfo = async (params) => {
    const res = await ApiOptions.editUserInfo(params);
    return res.code === 1 ? showToast("编辑成功") : showToast(res.message);
  };

  const choosePayWay = (payWay) => editUserInfo({ payWay });

  const uploadAvatar = async (file) => editUserInfo({ avatar: file });

  return { editUserInfo, choosePayWay, uploadAvatar };
};
